<template>
  <div class="data-page">
    <el-card>
      <template #header>
        <h3>数据展示</h3>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 抽取记录 -->
        <el-tab-pane label="抽取记录" name="extractions">
          <el-table 
            :data="extractions" 
            v-loading="loadingExtractions"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户" width="120" />
            <el-table-column prop="document" label="文档内容" show-overflow-tooltip />
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="text" @click="viewExtraction(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 实体数据 -->
        <el-tab-pane label="实体数据" name="entities">
          <div class="filter-section">
            <el-select v-model="entityTypeFilter" placeholder="筛选实体类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="设备名" value="设备名" />
              <el-option label="性能表征" value="性能表征" />
              <el-option label="故障状态" value="故障状态" />
              <el-option label="故障原因" value="故障原因" />
              <el-option label="解决办法" value="解决办法" />
            </el-select>
          </div>
          
          <el-table 
            :data="filteredEntities" 
            v-loading="loadingEntities"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="entity_type" label="实体类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getEntityTagType(row.entity_type)">
                  {{ row.entity_type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="entity_value" label="实体值" />
            <el-table-column prop="extraction_id" label="所属记录ID" width="120" />
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.created_at) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 关系数据 -->
        <el-tab-pane label="关系数据" name="relations">
          <el-table 
            :data="relations" 
            v-loading="loadingRelations"
            border
            stripe
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="subject" label="主体" width="200" />
            <el-table-column prop="predicate" label="关系" width="150">
              <template #default="{ row }">
                <el-tag type="success">{{ row.predicate }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="object" label="客体" width="200" />
            <el-table-column prop="extraction_id" label="所属记录ID" width="120" />
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.created_at) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 统计图表 -->
        <el-tab-pane label="统计图表" name="statistics">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card>
                <el-statistic title="总抽取记录数" :value="extractions.length" />
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card>
                <el-statistic title="总实体数" :value="entities.length" />
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card>
                <el-statistic title="总关系数" :value="relations.length" />
              </el-card>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <h4>实体类型分布</h4>
                </template>
                <div ref="entityChartRef" style="height: 300px"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <template #header>
                  <h4>关系类型分布</h4>
                </template>
                <div ref="relationChartRef" style="height: 300px"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="dialogVisible" title="抽取记录详情" width="800px">
      <div v-if="currentExtraction">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户">
            {{ currentExtraction.username }}
          </el-descriptions-item>
          <el-descriptions-item label="提示语">
            {{ currentExtraction.prompt }}
          </el-descriptions-item>
          <el-descriptions-item label="文档内容">
            {{ currentExtraction.document }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(currentExtraction.created_at) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <h4>抽取结果：</h4>
        <pre>{{ formatResult(currentExtraction.result) }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { extractAPI, dataAPI } from '../api'
import * as echarts from 'echarts'

const activeTab = ref('extractions')
const loadingExtractions = ref(false)
const loadingEntities = ref(false)
const loadingRelations = ref(false)

const extractions = ref([])
const entities = ref([])
const relations = ref([])

const entityTypeFilter = ref('')
const dialogVisible = ref(false)
const currentExtraction = ref(null)

const entityChartRef = ref(null)
const relationChartRef = ref(null)

const filteredEntities = computed(() => {
  if (!entityTypeFilter.value) {
    return entities.value
  }
  return entities.value.filter(e => e.entity_type === entityTypeFilter.value)
})

const getEntityTagType = (type) => {
  const types = {
    '设备名': 'primary',
    '性能表征': 'success',
    '故障状态': 'warning',
    '故障原因': 'danger',
    '解决办法': 'info'
  }
  return types[type] || ''
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

const formatResult = (result) => {
  try {
    return JSON.stringify(JSON.parse(result), null, 2)
  } catch {
    return result
  }
}

const loadExtractions = async () => {
  loadingExtractions.value = true
  try {
    const res = await extractAPI.getExtractions()
    if (res.success) {
      extractions.value = res.extractions
    }
  } catch (error) {
    ElMessage.error('加载抽取记录失败')
  } finally {
    loadingExtractions.value = false
  }
}

const loadEntities = async () => {
  loadingEntities.value = true
  try {
    const res = await dataAPI.getEntities()
    if (res.success) {
      entities.value = res.entities
    }
  } catch (error) {
    ElMessage.error('加载实体数据失败')
  } finally {
    loadingEntities.value = false
  }
}

const loadRelations = async () => {
  loadingRelations.value = true
  try {
    const res = await dataAPI.getRelations()
    if (res.success) {
      relations.value = res.relations
    }
  } catch (error) {
    ElMessage.error('加载关系数据失败')
  } finally {
    loadingRelations.value = false
  }
}

const viewExtraction = (row) => {
  currentExtraction.value = row
  dialogVisible.value = true
}

const renderCharts = async () => {
  await nextTick()
  
  // 实体类型分布图
  if (entityChartRef.value) {
    const entityChart = echarts.init(entityChartRef.value)
    const entityTypeCount = {}
    entities.value.forEach(e => {
      entityTypeCount[e.entity_type] = (entityTypeCount[e.entity_type] || 0) + 1
    })
    
    entityChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: Object.entries(entityTypeCount).map(([name, value]) => ({
          name,
          value
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    })
  }
  
  // 关系类型分布图
  if (relationChartRef.value) {
    const relationChart = echarts.init(relationChartRef.value)
    const relationTypeCount = {}
    relations.value.forEach(r => {
      relationTypeCount[r.predicate] = (relationTypeCount[r.predicate] || 0) + 1
    })
    
    relationChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: Object.keys(relationTypeCount),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        type: 'bar',
        data: Object.values(relationTypeCount),
        itemStyle: {
          color: '#67C23A'
        }
      }]
    })
  }
}

watch(activeTab, (newTab) => {
  if (newTab === 'statistics') {
    renderCharts()
  }
})

onMounted(async () => {
  await Promise.all([
    loadExtractions(),
    loadEntities(),
    loadRelations()
  ])
})
</script>

<style scoped>
.data-page {
  width: 100%;
  max-width: 100%;
}

.filter-section {
  margin-bottom: 20px;
}

pre {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow: auto;
  max-height: 400px;
}
</style>

